package org.benjamin.lending.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.*;
import org.benjamin.lending.repository.*;
import org.benjamin.lending.service.InnerMessageService;
import org.benjamin.lending.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Service("memebrService")
public class MemberServiceImpl implements MemberService {
	
	private final Logger logger = LogManager.getLogger();
	
	@Autowired
	private MemberInfoRepository memberInfoRepository;
	
	@Autowired
	private MemberStatusRepository memberStatusRepository;
	
	@Autowired
	private MemberMoneyRepository memberMoneyRepository;

	@Autowired
	private MemberMoneyLogRepository memberMoneyLogRepository;

	@Autowired
	private MemberIdentityRepository memberIdentityRepository;

	@Autowired
	private MemberPictureRepository memberPictureRepository;
	
	@Autowired
	private InnerMessageService innerMessagerService;
	
	@Autowired
	private LoginLogRepository loginLogRepository;

	/**
	 * 用户注册
	 */
	@Override
	public MemberInfo registerMember(MemberInfo memberInfo,String recommendCode) {
		logger.info("用户注册");
		boolean existUsername = this.memberInfoRepository.existsByUsername(memberInfo.getUsername());
		logger.info("查询当前用户名是否存在：{}",existUsername);
		Assert.isTrue(!existUsername,"当前用户名"+memberInfo.getUsername()+"已经存在，无法进行注册");
		this.memberInfoRepository.save(memberInfo);
		if(StringUtils.isNotBlank(memberInfo.getMobile())){
			logger.info("手机已经校验");
			MemberStatus memberStatus = new MemberStatus();
			memberStatus.setUid(memberInfo.getId());
			memberStatus.setPhoneStatus(true);
			this.memberStatusRepository.save(memberStatus);
		}
		if(StringUtils.isNotBlank(recommendCode)){
			logger.info("注册用户推荐好友");
			MemberInfo info = this.memberInfoRepository.findByRecommendCode(recommendCode);
			memberInfo.setRecommendUid(info.getId());
			this.memberInfoRepository.save(memberInfo);
		}
		logger.info("用户注册成功，用户ID编号为{}",memberInfo.getId());
		MemberMoney memberMoney = new MemberMoney();
		memberMoney.setUid(memberInfo.getId());
		this.memberMoneyRepository.save(memberMoney);
		logger.info("初始化用户金额信息完成");
		//发送站内信
		Map<String,Object> context = new HashMap<>();
		context.put("#USERNAME#", memberInfo.getUsername());
		this.innerMessagerService.sendMessage("恭喜您注册成功", "尊敬的 #USERNAME# 您好，恭喜您注册成功。",context,memberInfo);
		return memberInfo;
	}
	
	@Override
	public MemberInfo userLogin(String username){
		return this.memberInfoRepository.findByUsername(username);
	}
	
	

	@Override
	public MemberInfo getEntityId(Integer id,boolean loadMoney) {
		MemberInfo memberInfo = this.memberInfoRepository.findOne(id);
		return memberInfo;
	}

	@Override
	public MemberIdentity findIdentityByUsername(String username) {
		logger.info("通过用户名查询验证信息");
		MemberInfo memberInfo = this.memberInfoRepository.findByUsername(username);
		MemberIdentity memberIdentity = this.memberIdentityRepository.findOne(memberInfo.getId());
		return memberIdentity;
	}

	@Override
	public MemberMoney findByMoneyByUsername(String username) {
		logger.info("通过用户名查询用户金额");
		MemberInfo memberInfo = this.memberInfoRepository.findByUsername(username);
		return memberMoneyRepository.findOne(memberInfo.getId());
	}

	@Override
	public Page<MemberInfo> findMemberAll(Pageable pageable) {
		return this.memberInfoRepository.findAll(pageable);
	}

	@Override
	public void memberIdentitySuccess(Integer userId,String realName,String idNumber,String token,String pictureData){
		MemberIdentity memberIdentity = this.memberIdentityRepository.findOne(userId);
		Assert.notNull(memberIdentity,"");
		memberIdentity.setIdentityNumber(idNumber);
		memberIdentity.setRealName(realName);
		memberIdentity.setToken(token);
		this.memberIdentityRepository.save(memberIdentity);
		if(StringUtils.isNotBlank(pictureData)){
			logger.info("保存客户头像");
			MemberPicture memberPicture = new MemberPicture();
			memberPicture.setPicture(pictureData);
			memberPicture.setUid(userId);
			this.memberPictureRepository.save(memberPicture);
		}
	}


	@Override
	public void memberMoneyChange(Integer uid, BigDecimal amount, MemberMoneyLog.Type type, String createIp){
		MemberInfo memberInfo = this.memberInfoRepository.findOne(uid);
		this.memberMoneyChange(memberInfo,amount,type,createIp);
	}

	/**
	 * 用户资金变动
	 * @param memberInfo 用户对象
	 * @param amount 变动资金
	 * @param type 类型
	 * @param createIp IP地址
	 */
	@Override
	public void memberMoneyChange(MemberInfo memberInfo, BigDecimal amount, MemberMoneyLog.Type type, String createIp) {
		MemberMoney memberMoney = this.memberMoneyRepository.findOne(memberInfo.getId());
		MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
		memberMoneyLog.setAddTime(new Timestamp(System.currentTimeMillis()));
		memberMoneyLog.setAffectMoney(amount);
		memberMoneyLog.setType(type.toString());
		memberMoneyLog.setAddIp(createIp);
		memberMoneyLog.setAccountMoney(memberMoney.getAccountMoney());
		memberMoneyLog.setMemberInfo(memberInfo);
		switch (type){
			case RECHARGE:
				memberMoneyLog.setInfo("您已经成功充值了"+amount+"元");
				memberMoney.setAccountMoney(memberMoney.getAccountMoney().add(amount));
				break;
		}
		this.memberMoneyRepository.save(memberMoney);
		this.memberMoneyLogRepository.save(memberMoneyLog);
	}

	@Override
	public Page<MemberMoneyLog> findByMoneyLogsByUserId(Integer id,Pageable pageable) {
		MemberInfo memberInfo = this.memberInfoRepository.findOne(id);
		return this.memberMoneyLogRepository.findByMemberInfo(memberInfo,pageable);
	}

	@Override
	public Page<LoginLog> findLoginLog(String username) {
		Page<LoginLog> page = this.loginLogRepository.findAll(new PageRequest(0, 20));
		return page;
	}
}
